﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Localization;
using StackExchange.Redis;
using System.ComponentModel;
using TrafficWebApi.Models;
using TrafficWebApi.Models.Response;
using TrafficWebApi.Services;
using TrafficWebApi.Utils;
using Utils;

namespace TrafficWebApi.Controllers
{
    public class BaseController : ControllerBase
    {
        #region PageCls
        /// <summary>
        /// 返回结果
        /// </summary>
        public ResultJson resJson = new ResultJson();

        /// <summary>
        /// REDIS帮助类
        /// </summary>
        public RedisHelper? myRedisHelper { get; set; }
        /// <summary>
        /// REDIS数据库
        /// </summary>
        public IDatabase? redisDB { get; set; }
        /// <summary>
        /// 应用位置信息
        /// </summary>
        public IWebHostEnvironment? _environment { get; set; }
        /// <summary>
        /// 上下文
        /// </summary>
        public IHttpContextAccessor? _contextAccessor { get; set; }
        /// <summary>
        /// SignalR客户端
        /// </summary>
        public IHubContext<MessageHub>? _MessageHub { get; set; }
        /// <summary>
        /// 信息服务
        /// </summary>
        public MessageService? msgService { get; set; } = null;

        /// <summary>
        /// 多语言选择器
        /// </summary>
        public IStringLocalizer<Resource> Localizer { get; set; }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="redisHelper"></param>
        /// <param name="environment"></param>
        /// <param name="contextAccessor"></param>
        /// <param name="_messageHub"></param>
        /// <param name="_localizer"></param>
        public BaseController(RedisHelper redisHelper, IWebHostEnvironment environment, IHttpContextAccessor contextAccessor, IHubContext<MessageHub> _messageHub, IStringLocalizer<Resource> _localizer)
        {
            myRedisHelper = redisHelper;
            redisDB = myRedisHelper.GetDatabase();

            _environment = environment;
            _contextAccessor = contextAccessor;
            _MessageHub = _messageHub;
            this.msgService = new MessageService(_MessageHub);
            this.Localizer = _localizer;
        }
        #endregion

        #region 公共方法
        /// <summary>
        /// 返回JSON结果
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("ResponseJson")]
        public ActionResult ResponseJson()
        {
            string jsonStr = JsonHelper.ObjectToJson(this.resJson);
            return new ContentResult { Content = jsonStr, ContentType = "application/json" };
        }

        /// <summary>
        /// 返回401失效结果
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("Response401")]
        public ActionResult Response401()
        {
            var result = new JsonResult(this.resJson);
            result.StatusCode = StatusCodes.Status401Unauthorized;
            return result;
        }

        /// <summary>
        /// 返回文件下载，并删除文件。
        /// </summary>
        /// <param name="filePath">文件本地路径</param>
        /// <param name="fileName">下载时保存的文件名</param>
        /// <param name="isDel">是否于用户下载后删除文件</param>
        /// <param name="fileType"></param>
        /// <returns></returns>
        [HttpPost, Route("ResponseFile")]
        public ActionResult ResponseFile(string filePath, string fileName, bool isDel, string fileType = "")
        {
            if (filePath.IndexOf(".mp4") != -1 || filePath.ToLower().IndexOf(".html") != -1)
            {
                return PhysicalFile(filePath, string.IsNullOrEmpty(fileType) ? "application/octet-stream" : fileType, fileName, true);
            }
            else
            {
                ActionResult fileResult = File(System.IO.File.ReadAllBytes(filePath), fileType != "" ? fileType : "application/octet-stream", fileName);
                if (isDel)
                {
                    FileInfo info = new FileInfo(filePath);
                    info.Delete();
                }
                return fileResult;
            }
        }

        /// <summary>
        /// 获取描述字段
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        [HttpPost, Route("GetDescription")]
        public string GetDescription(object value)
        {
            if (value == null) return string.Empty;

            Type type = value.GetType();
            var fieldInfo = type.GetField(Enum.GetName(type, value));
            if (fieldInfo != null)
            {
                if (Attribute.IsDefined(fieldInfo, typeof(DescriptionAttribute)))
                {
                    var description = Attribute.GetCustomAttribute(fieldInfo, typeof(DescriptionAttribute)) as DescriptionAttribute;
                    if (description != null) return description.Description;
                    else return string.Empty;
                }
            }
            return string.Empty;
        }

        ///// <summary>
        ///// 获取用户信息
        ///// </summary>
        //[HttpPost, Route("GetUserData")]
        //public void GetUserData()
        //{
        //    try
        //    {
        //        var tokenHeader = HttpContext.Request.Headers["Authorization"].ToString().Replace("Bearer ", "");
        //        var user = JwtHelper.SerializeJwt(tokenHeader);

        //        this.UserData = UserBll.GetModel(int.Parse(user.Uid));
        //        if (this.UserData != null)
        //        {
        //            this.UserData.Token = tokenHeader;
        //            this.UserData.CompanyData = CompanyBll.GetModel(this.UserData.CompanyID);
        //            if (this.UserData.Depart_ID != 0)
        //            {
        //                this.UserData.DepartData = DepartBll.GetModel(this.UserData.Depart_ID);
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        WriteLog(this.GetType().ToString(), ex.Message);
        //    }
        //}
        #endregion
    }
}